package com.xyzwps.paimon.furina.modules.me

import com.xyzwps.paimon.furina.common.DateTimeUtil
import com.xyzwps.paimon.furina.modules.auth.entity.UserAccount
import com.xyzwps.paimon.furina.modules.userinfo.entity.UserInfo
import com.xyzwps.paimon.furina.modules.userinfo.entity.UserInfoRepository
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.transactions.transaction
import org.springframework.stereotype.Component

@Component
class MeApplication(
    private val userInfoRepository: UserInfoRepository,
    private val db: Database
) {

    fun getRichMeInfo(account: UserAccount): RichMeInfoDTO = getRichMeInfo(account.id)

    fun getRichMeInfo(userId: Long): RichMeInfoDTO = transaction(db) {
        makeRichMeInfo(userId)
    }

    fun updateMeUserInfo(userId: Long, body: UpdateMeUserInfoPayload): RichMeInfoDTO = transaction(db) {
        val userInfo = userInfoRepository.findByUserId(userId) ?: UserInfo.empty(userId)
        val newUserInfo = userInfo.copy(
            nickname = body.nickname,
            avatar = body.avatar,
            description = body.description,
            updateTime = DateTimeUtil.currentLocalDateTime()
        )
        userInfoRepository.upsert(newUserInfo)
        makeRichMeInfo(userId, userInfo = newUserInfo)
    }

    private fun makeRichMeInfo(userId: Long, userInfo: UserInfo? = null): RichMeInfoDTO {
        val theUserInfo = userInfo ?: userInfoRepository.findByUserId(userId)
        return RichMeInfoDTO(
            userId = userId,
            info = if (theUserInfo == null) null else MeUserInfoDTO(theUserInfo)
        )
    }

}